<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if(!class_exists('CI_Model')) { class CI_Model extends Model {} }

class Catalog_model extends CI_Model {
	var $perpage = 12;
	var $url;
	public function __construct() {
	   parent::__construct();
	   $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
	   $this->url = $this->uri->segment(1);
	}
	function index($args) {
		return $this->category($args);
	}
	function category($args) {
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$post_data = $this->input->post();
		}
		$data['url'] = $this->url;
		$data['id'] = $id = $args[0];
		$data['intag'] = $intag = $this->input->get('tag');
		if ($id == "") $data['id'] = $id = 0;
		/* parents */
		$this->db->select()->from('catalog_parents')->where('parent_status', 1);
		$this->db->where('parent_parent', $id);
		$this->db->order_by('parent_order', 'asc');
		$data['pages'] = $pages = $this->db->get()->result_array();
		/* parents */

		/* items */

		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = '0';
		if ($from === "all") {
			$this->db->from('catalog_items');
			$this->db->where('item_status', 1);
			$this->db->where('item_parent', $id);
			$this->perpage = $this->db->count_all_results();
			$from = '0';
		}
		$data['order'] = $order = $this->input->get('order', true);
		if ($order == "") $data['order'] = $order = "order";
		$data['side'] = $side = $this->input->get('side', true);
		if ($side == "") $data['side'] = $side = "asc";
		$data['brand'] = $brand = $this->input->get('brand', true);
		$data['custom_1'] = $custom_1 = $this->input->get('custom_1', true);
		$data['custom_2'] = $custom_2 = $this->input->get('custom_2', true);
		$data['price_from'] = $price_from = $this->input->get('price_from', true);
		$data['price_to'] = $price_to = $this->input->get('price_to', true);


		$this->db->select()->from('catalog_items');
		$this->db->where('item_status', 1);
		$this->db->where('item_parent', $id);
		if ($brand) $this->db->where('item_brand', $brand);
		if ($custom_1) $this->db->where('item_custom_field_1', $custom_1);
		if ($custom_2) $this->db->where('item_custom_field_2', $custom_2);
		if ($price_from && is_numeric($price_from) && $price_to && is_numeric($price_to)) {
			$this->db->where('item_price >= ', $price_from);
			$this->db->where('item_price <= ', $price_to);
		} else {
			if ($price_from && is_numeric($price_from)) $this->db->where('item_price >= ', $price_from);
			if ($price_to && is_numeric($price_to)) $this->db->where('item_price <= ', $price_to);
		}
		$this->db->order_by('item_'.$order, $side);
		$this->db->limit($this->perpage, $from);
		$data['items'] = $items = $this->db->get()->result_array();

		/* IMAGES */
		if (sizeof($items) > 0) {
			foreach ($items as $it) {
				$ids[] = $it['item_id'];
			}
			$aimages = $this->db->select()->from('catalog_images')->where_in('photo_item', $ids)->where('photo_main', 1)->get()->result_array();
			foreach ($aimages as $aim) {
				$data['aimages'][$aim['photo_item']] = $aim;
			}
		}
		/* IMAGES */
		/* OPINIONS */
//		if (sizeof($items) > 0) {
//			$aopinions = $this->db->select()->from('catalog_opinions')->where_in('opinion_item', $ids)->where('opinion_status', 1)->get()->result_array();
//			foreach ($aopinions as $aim) {
//				if (key_exists($aim['opinion_item'], $data['aopinions'])) {
//					$data['aopinions'][$aim['opinion_item']] += 1;
//				} else {
//					$data['aopinions'][$aim['opinion_item']] = 1;
//				}
//			}
//		}
		/* OPINIONS */

		/* TYPES */
		$atypes = $this->db->select('item_custom_field_1')->from('catalog_items')->where('item_parent', $id)->where('item_status', '1')->group_by('item_custom_field_1')->get()->result_array();
		$stypes = $this->db->select('item_custom_field_2')->from('catalog_items')->where('item_parent', $id)->where('item_status', '1')->group_by('item_custom_field_2')->get()->result_array();
		/* TYPES */

		/* items */

//		pagination
		$this->db->select()->from('catalog_items');
		$this->db->where('item_status', 1);
		$this->db->where('item_parent', $id);
		if ($brand) $this->db->where('item_brand', $brand);
		if ($custom_1) $this->db->where('item_custom_field_1', $custom_1);
		if ($custom_2) $this->db->where('item_custom_field_2', $custom_2);
		if ($price_from && is_numeric($price_from) && $price_to && is_numeric($price_to)) {
			$this->db->where('item_price >= ', $price_from);
			$this->db->where('item_price <= ', $price_to);
		} else {
			if ($price_from && is_numeric($price_from)) $this->db->where('item_price >= ', $price_from);
			if ($price_to && is_numeric($price_to)) $this->db->where('item_price <= ', $price_to);
		}
		$count = $this->db->count_all_results();

		if ($from != 0 && sizeof($items) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect($this->url.'/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/'.$this->uri->uri_string;
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$config['next_link'] = '<img src="/data/i/next.png" alt="" title="" />';
		$config['prev_link'] = '<img src="/data/i/prev.png" alt="" title="" />';
		$config['next_tag_open'] = '<div class="nextpage">';
		$config['next_tag_close'] = '</div>';
		$config['prev_tag_open'] = '<div class="prevpage">';
		$config['prev_tag_close'] = '</div>';
		$config['last_tag_open'] = '<div class="prevpage">';
		$config['last_tag_close'] = '</div>';
		$config['first_tag_open'] = '<div class="prevpage">';
		$config['first_tag_close'] = '</div>';
		$config['show_all'] = TRUE;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
//		 pagination

		if ($this->config->item('catalog_show_needauth') == true && !$this->ion_auth->logged_in()) $data['show_a'] = false; else $data['show_a'] = true;

		if ($id != 0) {
			$data['catalog_active_category'] = $out['data']['catalog_active_category'] = $active = $this->db->select()->from('catalog_parents')->where('parent_id', $id)->get()->row_array();
			if ($active['parent_meta'] != "") $out['data']['title'] = $active['parent_meta'];
			if ($active['parent_metadesc'] != "") $out['data']['desc'] = $active['parent_metadesc'];
			if ($active['parent_metakey'] != "") $out['data']['keys'] = $active['parent_metakey'];

			$out['data']['crumps'] = $this->catalog_service_model->getCrumps($active['parent_path'], $this->url."/category");
		}
		if($id == 0){
			$out['text'] = $this->load->view('modules/catalog/index', $data, true);
		} else {
			$check_items = $this->db->select()->from('catalog_items')->where('item_parent', $id)->where('item_status', '1')->get()->result_array();
			foreach ($check_items as $u) {
				$book_check_items[] = $u['item_brand'];
			}
			if (sizeof($check_items) > 0) {
			$brands = $this->db->select()->from('catalog_brands')->where('brand_status',1)->where_in('brand_id', $book_check_items)->get()->result_array();
			$form = new jQuickForm('sorts', 'GET');
			$select = $form->insertSelect('order')->addClass('colored_select')->setLabel('Сортировать');
			$select->addOption('По порядку','order');
			$select->addOption('По цене','price');
			$select->addOption('По названию','title');

			$form->insertInputText('price_from')->setLabel('Цена от');
			$form->insertInputText('price_to')->setLabel('До');

			$select = $form->insertSelect('brand')->addClass('colored_select');
			$select->addOption("Бренд", "");
			foreach ($brands as $brand) {
				$select->addOption($brand['brand_title'], $brand['brand_id']);
			}

			$select = $form->insertSelect('custom_1')->addClass('colored_select');
			$select->addOption(($active['parent_custom_field_1']?$active['parent_custom_field_1']:"Параметры"), "");
			foreach ($atypes as $atype) {
				if ($atype != "")
				$select->addOption($atype['item_custom_field_1'], $atype['item_custom_field_1']);
			}

			$select = $form->insertSelect('custom_2')->addClass('colored_select');
			$select->addOption(($active['parent_custom_field_2']?$active['parent_custom_field_2']:"Параметры"), "");
			foreach ($stypes as $stype) {
				if ($stype != "")
				$select->addOption($stype['item_custom_field_2'], $stype['item_custom_field_2']);
			}
			$form->insertInputSubmit("Выбрать");
			$form->insertStatic("<br class='cc' />");
			$form->addDataSource(new HTML_QuickForm2_DataSource_Array($post_data));

			$data['sort_form'] = $form.'';
			$data['sort_js'] = jQuickForm::js()->getJsAll();
			$out['data']['onecol'] = true;
			}
			$out['text'] = $this->load->view('modules/catalog/category', $data, true);
		}
		return $out;
	}
	function show($args) {
		if ($this->config->item('catalog_show_needauth') == true && !$this->ion_auth->logged_in()) redirect('/');
		$data['url'] = $this->url;
		$id = $args[0];
		if ($this->config->item('catalog_show_needauth') == true && !$this->ion_auth->logged_in()) $data['show_a'] = false; else $data['show_a'] = true;
		$data['page'] = $page = $this->db->select()->from('catalog_items')->where('item_id',$id)->limit(1)->get()->row_array();
		if (sizeof($page) <= 0 || $page['item_status'] == 0) redirect('/');

		/* IMAGES */
		$data['images'] = $this->db->select()->from('catalog_images')->where('photo_item', $id)->order_by('photo_order', 'asc')->get()->result_array();
		/* IMAGES */

		/* TOGETHER */
		$together = $data['together'] = $this->db->select("catalog_items.*")->from('catalog_together')->where('together_item', $id)->join('catalog_items', 'catalog_together.together_value = catalog_items.item_id', 'left')->get()->result_array();
		if (sizeof($together) > 0) {
			foreach ($together as $it) {
				$ids[] = $it['item_id'];
			}
		}
		/* TOGETHER */

		if (sizeof($ids) > 0) {

			$aimages = $this->db->select()->from('catalog_images')->where_in('photo_item', $ids)->where('photo_main', 1)->get()->result_array();
			foreach ($aimages as $aim) {
				$data['aimages'][$aim['photo_item']] = $aim;
			}
		}

		/* TOGETHER */

		/* OPINIONS
			$data['opinions'] = $this->db->select()->from('catalog_opinions')->where('opinion_item', $id)->where('opinion_status', 1)->order_by('opinion_date', 'desc')->get()->result_array();
			$form = new jQuickForm('opinion_simple');

			$fieldset = $form->insertFieldset();

			$gr = $fieldset->insertGroup()->addClass('col col2');
			$gr->insertInputText('opinion_name')->setLabel('Ваше имя')->addRuleRequired();

			/*$email = $gr->insertInputText('opinion_email')->setLabel('Эл. почта');
			$email->addRule('callback', 'Не верный формат', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::CLIENT);
			$email->addRule('callback', 'Не верный формат', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::SERVER);
			$email->addRuleRequired();

			$gr = $fieldset->insertGroup()->addClass('no-bottom-margin');
			$gr->insertStatic('
			<div class="opinion_text-0">
				<img class="smile" alt=":D" src="/data/images/smiles/laugh.gif"/>
				<img class="smile" alt=":lol:" src="/data/images/smiles/lol.gif"/>
				<img class="smile" alt=":-)" src="/data/images/smiles/smile.gif"/>
				<img class="smile" alt=";-)" src="/data/images/smiles/wink.gif"/>
				<img class="smile" alt="8)" src="/data/images/smiles/cool.gif"/>
				<img class="smile" alt=":-|" src="/data/images/smiles/normal.gif"/>
				<img class="smile" alt=":-*" src="/data/images/smiles/whistling.gif"/>
				<img class="smile" alt=":oops:" src="/data/images/smiles/redface.gif"/>
				<img class="smile" alt=":sad:" src="/data/images/smiles/sad.gif"/>
				<img class="smile" alt=":cry:" src="/data/images/smiles/cry.gif"/>
				<img class="smile" alt=":o" src="/data/images/smiles/surprised.gif"/>
				<img class="smile" alt=":-?" src="/data/images/smiles/confused.gif"/>
				<img class="smile" alt=":-x" src="/data/images/smiles/sick.gif"/>
				<img class="smile" alt=":eek:" src="/data/images/smiles/shocked.gif"/>
				<img class="smile" alt=":zzz" src="/data/images/smiles/sleeping.gif"/>
				<img class="smile" alt=":P" src="/data/images/smiles/tongue.gif"/>
				<img class="smile" alt=":roll:" src="/data/images/smiles/rolleyes.gif"/>
				<img class="smile" alt=":sigh:" src="/data/images/smiles/unsure.gif"/>
			</div>
			');
			$gr->insertTextArea('opinion_text')->setLabel('Мнение о товаре')->addRuleRequired();



			if ($this->ion_auth->logged_in()) {
				$user = $this->ion_auth->get_user();
				$have_data['opinion_name'] = $user->first_name." ".$user->last_name;
				$have_data['opinion_phone'] = $user->phone;
				$have_data['opinion_email'] = $user->email;
			} else {
				$this->tools_model->captcha($form);
			}

			if ($_SERVER['REQUEST_METHOD'] == "POST") {
				if ($form->validate()) {
					$mail_data = $p_data = $this->input->post();
					$this->load->library('email');
					if ($this->ion_auth->logged_in()) {
						$mail_data['user'] = $user = $this->ion_auth->get_user();
						$mail_data['opinion_user'] = $user->id;
					}
					$mail_data['item'] = $page;
					$msg = $this->load->view('modules/catalog/feedback_email', $mail_data, true);

					$this->email->from($this->config->item('from_email'), $this->config->item('from_name'));
					$this->email->to($this->config->item('admin_email'));
					$this->email->subject('Новый отзыв с сайта '.$this->config->item('company_name'));
					$this->email->message($msg);

					if ($this->email->send()) {
						$this->session->set_flashdata('msg', 'Спасибо, Ваше мнение отправлено. После проверки администратором, появится на этой странице.');
					} else {
						$this->session->set_flashdata('msg', 'Ошибка отправки сообщения.');
					}

					$hidden = sha1("soltbyme".$this->session->userdata('session_id')."mybigsolthash");
					$hidden2 = sha1("soltbyme".$this->session->userdata('session_id')."myhashsolt");
					unset($mail_data[$hidden]);
					unset($mail_data[$hidden2]);
					unset($mail_data['user']);
					unset($mail_data['item']);
					$mail_data['opinion_id'] = 0;
					$mail_data['opinion_item'] = $id;
					$mail_data['opinion_date'] = time();
					$mail_data['opinion_status'] = 0;
					$mail_data['opinion_ip'] = $this->input->ip_address();
					$this->db->insert('catalog_opinions', $mail_data);
					redirect(mb_substr($this->catalog_service_model->get_item_link($id),1));
				} else {
					$data['f'] = true;
				}

			}

			$form->insertInputSubmit('Отправить');

			$form->addDataSource(new HTML_QuickForm2_DataSource_Array($have_data));
			$data['form'] = $form."";
			$data['js'] = jQuickForm::js()->getJsAll();


		/* OPINIONS */

		$data['catalog_active_category'] = $out['data']['catalog_active_category'] = $active = $this->db->select()->from('catalog_parents')->where('parent_id', $page['item_parent'])->get()->row_array();
		$out['data']['crumps'] = $this->catalog_service_model->getCrumps($active['parent_path'], $this->url."/category")." &raquo; <a href='/catalog/".$this->catalog_service_model->get_item_link($page['item_id'])."/'>".$page['item_title']."</a>";
		if ($page['item_pagetitle'] != "") { $out['data']['title'] = $page['item_pagetitle'];	} else { $out['data']['title'] = "Купить ".$page['item_title']." ";	}
		if ($page['item_pagedesc'] != "") { $out['data']['desc'] = $page['item_pagedesc'];	}
		if ($page['item_pagekeys'] != "") { $out['data']['keys'] = $page['item_pagekeys'];	}
		$out['text'] = $this->load->view('modules/catalog/show', $data, true);
		return $out;
	}
	function search() {
		if ($_SERVER['REQUEST_METHOD'] == "POST") {
			if ($this->config->item('catalog_show_needauth') == true && !$this->ion_auth->logged_in()) $data['show_a'] = false; else $data['show_a'] = true;
			$in = $this->input->post('text');
			$atext = explode(" ", $in);
			$this->db->select()->from('catalog_items');
			$this->db->where('item_status', 1);
			$this->db->order_by('item_title', 'asc');
				foreach ($atext as $text) {
					if ($text != "")
					$this->db->or_like('item_title', $text);
				}
			$data['items'] = $items = $this->db->get()->result_array();
			/* IMAGES */
			if (sizeof($items) > 0) {
				foreach ($items as $it) {
					$ids[] = $it['item_id'];
				}
				$aimages = $this->db->select()->from('catalog_images')->where_in('photo_item', $ids)->where('photo_main', 1)->get()->result_array();
				foreach ($aimages as $aim) {
					$data['aimages'][$aim['photo_item']] = $aim;
				}
			}
			/* IMAGES */
			$out['text'] = $this->load->view('modules/catalog/results', $data, true);
			$out['data']['crumps'] = " &raquo; <a href='/".$this->url."/search/'>Поиск товаров</a>";
			$out['data']['title'] = "Купить ".$in;
			return $out;
		} else {
			$out['text'] = showmenotice('Ничего не найдено, попробуйте изменить свой запрос.');
			$out['data']['crumps'] = " &raquo; <a href='/".$this->url."/search/'>Поиск товаров</a>";
			return $out;
		}
	}
	function homepage() {
		$data['catalog_parents'] = $this->db->select()->from('catalog_parents')->where('parent_show_in_mainpage', 1)->where('parent_status',1)->get()->result_array();
//		$data['catalog_news'] = $catalog_news = $this->db->select()->from('catalog_items')->where('item_status', '1')->where('item_show_in_mainpage', '1')->order_by('RAND()')->limit(15)->get()->result_array();
		$data['news'] = $this->db->select()->from('news')->where('news_status', '1')->where('news_parent', 2)->order_by('news_id', 'desc')->limit(3)->get()->result_array();
		$data['homepage'] = $this->db->select()->from('content')->where('page_curl', 'homepage')->get()->row_array();
		//$data['catalog_hits'] = $catalog_hits = $this->db->select()->from('catalog_items')->where('item_status', '1')->where('item_hit', '1')->order_by('RAND()')->get()->result_array();
			/* IMAGES */
			if (sizeof($catalog_news) > 0) {
				foreach ($catalog_news as $it) {
					$ids[] = $it['item_id'];
				}
			}
			if (sizeof($ids) > 0) {
				$aimages = $this->db->select()->from('catalog_images')->where_in('photo_item', $ids)->where('photo_main', 1)->get()->result_array();
				foreach ($aimages as $aim) {
					$data['aimages'][$aim['photo_item']] = $aim;
				}
			}
			/* IMAGES */
		if ($this->config->item('catalog_show_needauth') == true && !$this->ion_auth->logged_in()) $data['show_a'] = false; else $data['show_a'] = true;
		$data['url'] = 'catalog';
		$out['text'] = $this->load->view('modules/catalog/homepage', $data, true);
		return $out;
	}
	function feedback() {
		$data['pages'] = $this->db->select()->from('catalog_opinions')->where("opinion_shop != ''")->where('opinion_status', '1')->get()->result_array();
		$out['text'] = $this->load->view('modules/catalog/opinions_shop', $data, true);
		return $out;
	}
        public function search_form(){
		$form = new jQuickForm('search');
		$form->setAttribute('action', '/catalog/search/');
		$form->insertInputText('text')->setPlaceholder('Введите название товара')->AddRuleRequired();
		$form->insertInputSubmit("Искать");
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		return $data;
	}
}
